package stud.aistar.controller;

import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import stud.aistar.entity.*;
import stud.aistar.service.*;
import stud.aistar.util.DateUtil;
import stud.aistar.util.SmsUtil;
import stud.aistar.vo.AgeVo;
import stud.aistar.vo.MedicalVo;
import stud.aistar.vo.NumVo;
import stud.aistar.vo.OrderVo;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @version 1.0
 * @Auther: GIT:liming  -  jybdd
 * @Description - 本类用于: 个人中心
 * @Date: 2019/9/30 17:43
 */
@Controller
@RequestMapping("/personal")
@SuppressWarnings("all")
public class UserInfoController {

    //注入用户详情
    @Autowired
    private IUserInfoService UserInfoService;

    //注入挂号
    @Autowired
    private IRegOfficeService regOfficeService;

    //注入订单
    @Autowired
    private IOrderVoService orderVoService;

    //注入一级科室
    @Autowired
    private IDepartmentService departmentService;

    //注入二级科室
    @Autowired
    private ISecondDepartmentService secondDepartmentService;

    //注入医生
    @Autowired
    private IDoctorService doctorService;

    //注入工作时间
    @Autowired
    private IWorkTimeService workTimeService;

//    注入时间
    @Autowired
    private ITimeService timeService;

    //注入支付宝
    @Autowired
    private IPayService payService;

    //注入医生信息-医生建议
    @Autowired
    private ITreatmentService treatmentService;

    //注入图像
    @Autowired
    private IImagesService imagesService;

    //注入病历
    @Autowired
    private IMedicalVoService medicalVoService;

    @Autowired
    private IPhoneService phoneService;

    @Autowired
    private ICommentService commentService;


    /**
     * NO. 0011 - liming
     * 进入个人中心
     * @param req
     * @return
     */
    @RequestMapping("/user")
    public String user(Model model,HttpSession session){
        User user = (User) session.getAttribute("user");
        List<Image> image = imagesService.findByUserId(user.getId());
//        session.setAttribute("userinfo",userinfo);
//        session.setAttribute("user",user);
        model.addAttribute("image",image);
        return "personal/myinfo";
    }

    /**
     * NO. 0012 - liming
     * 点击完善个人资料
     * @param req
     * @return
     */
    @RequestMapping("/site")
    public String site(){
        return "personal/myinfosite";
    }

    /**
     * NO. 0013 - liming
     * 插入实名信息
     * @param userinfo
     * @param httpSession
     * @param req
     * @return
     */
    @RequestMapping("/initup")
    public String initup(Userinfo userinfo, HttpSession httpSession,HttpServletRequest req){
        User users = (User) httpSession.getAttribute("user");
        //保存UserId
        userinfo.setUserId(users.getId());
        //保存姓名
        String resName = req.getParameter("resName");
        userinfo.setUname(resName);
        //保存身份证号
        String resCardNumber = req.getParameter("resCardNumber");
        userinfo.setIdcard(resCardNumber);
        //保存性别
        String resSex = req.getParameter("resSex");
        userinfo.setSex(resSex);
        //保存年龄
        AgeVo ageVo = UserInfoService.findCardYear(resCardNumber);
        Integer age = (Integer.parseInt(ageVo.getNowyear()) - Integer.parseInt(ageVo.getCardyear()));
        userinfo.setAge(age);
        userinfo.setTypes(0);
        UserInfoService.save(userinfo);
        httpSession.setAttribute("userinfo",userinfo);
        return "redirect:user";
    }

    /**
     * NO. 0031 - liming
     * 就诊记录及分页
     * @return
     */
    @RequestMapping("/record")
    public  String record() {
        return "personal/recording";
    }
    @RequestMapping("/records")
    public String records(Model model, HttpSession httpSession,@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "3") Integer pageSize){
        User user = (User) httpSession.getAttribute("user");
        List<OrderVo> orderVos = orderVoService.findByPids(user.getId());
        PageInfo<OrderVo> pageInfo = orderVoService.findByPids(user.getId(),Integer.valueOf(pageNum),Integer.valueOf(pageSize));
        System.out.println(pageInfo);
        model.addAttribute("orderVos",pageInfo);
        return "personal/pagedate/recordingPageDate";
    }

    @RequestMapping("/comment")
    public String com(HttpServletRequest request,HttpSession session){
        String comment = request.getParameter("com");
        String doctorId = request.getParameter("doctorId");
        User user = (User) session.getAttribute("user");
        Comment com = new Comment();
        com.setUserId(user.getId());
        com.setDoctorId(Integer.valueOf(doctorId));
        com.setComment(comment);
        com.setCreateTime(DateUtil.getCurrentTime());
        commentService.Insert(com);
        return "personal/recording";
    }

    /**
     * NO. 0041
     * 我的病历及分页 - liming
     * @return
     */
    @RequestMapping("/medical")
    public String medical(){
        return "personal/medicalrecord";
    }
    @RequestMapping("medicals")
    public String medicals(Model model, HttpSession httpSession,@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "4") Integer pageSize){
        User user = (User) httpSession.getAttribute("user");
        List<MedicalVo> medicalVos = medicalVoService.findByUsersId(user.getId());
        PageInfo<MedicalVo> pageInfo = medicalVoService.findByUsersId(user.getId(),Integer.valueOf(pageNum),Integer.valueOf(pageSize));
        model.addAttribute("medicalVos",pageInfo);
        return "personal/pagedate/medPageDate";
    }

    /**
     * NO. 0042 - liming
     * 上传病历、查看病历
     * @param model
     * @param req
     * @return
     */
    @RequestMapping("/medup")
    public String medup(Model model,HttpServletRequest req){
        String iname = req.getParameter("iname");
        model.addAttribute("iname",iname);
        return "personal/medical/medup";
    }
    @RequestMapping("/medtotal")
    public String metotal(){
        return "personal/medical/medtotal";
    }
    @RequestMapping("/medmore")
    public String medmore(Model modle,HttpServletRequest req){
        String mid = req.getParameter("mid");
        MedicalVo medicalVo = medicalVoService.findByMid(Integer.valueOf(mid));
        modle.addAttribute("medicalVo",medicalVo);
        return "personal/medical/medmore";
    }

    /**
     * NO. 0051 - liming
     * 账户安全
     * @return
     */
    @RequestMapping("/safetys")
    public String safety(){
        return "personal/safety";
    }

    /**
     * NO. 0052 - liming
     * 账户安全设置
     * @return
     */
    @RequestMapping("/safetysite")
    public String safetysite(){
        return "personal/safetyphone";
    }

    /**
     * NO. 0053 - liming
     * 更改手机号
     * @param req
     * @return
     */
    @RequestMapping("/safetyphone")
    public String safetyphone(HttpServletRequest req,HttpSession httpSession){
        User users = (User) httpSession.getAttribute("user");
        User user = UserInfoService.findById(users.getId());
        String phone = req.getParameter("phone");
        user.setPhone(phone);
        UserInfoService.update(user);
        return "redirect:user";
    }

    /**
     * NO. 0054 - liming
     * 密码设置
     * @return
     */
    @RequestMapping("/safetypassword")
    public String safetypass(){
        return "personal/safetypassword";
    }

    /**
     * NO. 00055 - liming
     * 密码设置保存
     * @param req
     * @param httpSession
     * @return
     */
    @RequestMapping("/safetypasssite")
    public String safetypassword(Model model,HttpServletRequest req,HttpSession httpSession){
        User users = (User) httpSession.getAttribute("user");
        User user = UserInfoService.findById(users.getId());
        //旧密码是否正确,判断数据库是否存在
        //新密码是否符合格式
        //新密码两次输入是否一致
        String ordPass = req.getParameter("ordPass");
        String newPass = req.getParameter("newPass");
        String again = req.getParameter("again");
        if (!ordPass .equals(user.getPassword())){
            String passerror = "原密码输入有误,请重新输入";
            model.addAttribute("passerror",passerror);
            System.out.println(ordPass+":"+user.getPassword());
            return "personal/safetypassword";

        }else {
            user.setPassword(newPass);
            UserInfoService.update(user);
            return "/showmessage/login";
        }
    }

    /**
     * NO. 0021 - liming
     * 订单及订单分页
     * @param modle
     * @param httpSession
     * @return
     */
    @RequestMapping("/order")
    public String order(){
        return "personal/order";
    }
    @RequestMapping("/orders")
    public String orders(Model model, HttpSession httpSession,@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "3") Integer pageSize){
        User user = (User) httpSession.getAttribute("user");
        List<Integer> inte = new ArrayList<>();
        List<RegOffice> regOffices = regOfficeService.findByUserId(user.getId());
        PageInfo<OrderVo> pageInfo = orderVoService.findByPid(user.getId(),Integer.valueOf(pageNum),Integer.valueOf(pageSize));
        Iterator<RegOffice> iter = regOffices.iterator();
        while (iter.hasNext()){
            RegOffice o = iter.next();
            List<NumVo> numVos = orderVoService.findList(o.getTimeId(),o.getDoctorId());
            Iterator<NumVo> numVo = numVos.iterator();
            while (numVo.hasNext()){
                NumVo n = numVo.next();
                if (o.getPatientId().equals(n.getPatientId())){
                    inte.add(n.getIndex());
                }
            }
        }
        model.addAttribute("inte",inte);
        model.addAttribute("orderVos",pageInfo);
        return "personal/pagedate/orderPageDate";
    }


    /**
     * NO. 0022 - liming
     * 订单详情
     * @return
     */
    @RequestMapping("/orderdetails")
    public String details(Model modle,HttpServletRequest req){
        String Oid = req.getParameter("Oid");
        Pay pay = payService.findByRegId(Integer.valueOf(Oid));
        OrderVo orderVos = orderVoService.findByOId(Integer.valueOf(Oid));
        Userinfo userInfo = UserInfoService.findByUserInfoId(orderVos.getPatientId());
        modle.addAttribute("userinfo",userInfo);
        modle.addAttribute("pay",pay);
        modle.addAttribute("orderVos",orderVos);
        return "personal/orderdetails";
    }

    /**
     * NO. 0022-1 - liming
     * 退号
     * @param modle
     * @param req
     * @return
     */
    @RequestMapping("/push")
    public String push(HttpServletRequest req){
        String Oid = req.getParameter("Oid");
        orderVoService.updateByOId(Integer.valueOf(Oid));
        return "redirect:order";
    }


    /**
     * NO. 0022-2 - liming
     * 更该科室提交页
     * @param model
     * @param req
     * @return
     */
    @RequestMapping("/change")
    public String change(Model model,HttpServletRequest req){
        String Oid = req.getParameter("Oid");
        RegOffice regOffice = regOfficeService.findById(Integer.valueOf(Oid));
        OrderVo orderVos = orderVoService.findByOId(Integer.valueOf(Oid));
        Userinfo userInfo = UserInfoService.findByUserInfoId(orderVos.getPatientId());
        model.addAttribute("userinfo",userInfo);
        model.addAttribute("regOffice",regOffice);
        model.addAttribute("orderVos",orderVos);
        return "personal/orderchange";
    }

    /**
     * NO. 0022-3 - liming
     * 更该科室下拉框组
     * @param model
     * @param fid
     * @param sid
     * @param did
     * @param tid
     * @param req
     * @return
     */
    @RequestMapping ("/option")
    public String into(Model model,String fid,String sid,String did,String tid){

        List<Department> list= departmentService.findAll();
        model.addAttribute("firstdep",list);
        //一级科室
        Integer firstId= null;
        if (fid==null||"-1".equals(fid)){
            firstId = null;
        }else {
            firstId = Integer.valueOf(fid);
            List<SecondDepartment> secList = secondDepartmentService.findByDeptId(firstId);
            model.addAttribute("seconddep",secList);
            model.addAttribute("fristId",firstId);
        }
        //二级科室
        Integer secondId=null;
        if (sid==null||"-1".equals(sid)){
            secondId=null;
        }else {
            secondId = Integer.valueOf(sid);
            List<Doctor> docList = doctorService.findBySdeptId(secondId);
            model.addAttribute("docList",docList);
            model.addAttribute("secondId",secondId);
        }
        //医生
        Integer doctorId = null ;
        List<Time> timeList =new ArrayList<>();
        if (did==null||"-1".equals(did)){
            doctorId = null;
        }else {
            doctorId = Integer.valueOf(did);
            List<WorkTime> wList = workTimeService.findByDocId(doctorId);

            Iterator<WorkTime> iter = wList.iterator();
            while (iter.hasNext()){
                WorkTime w= iter.next();
                Time t = timeService.findById(w.getTimeId());
                timeList.add(t);
                model.addAttribute("timeList",timeList);
                model.addAttribute("doctorId",doctorId);
            }
        }
        //时间
        Integer TimeId = null;
        if (tid == null ||"-1".equals(tid)){
            TimeId = null;
        }else{
            TimeId = Integer.valueOf(tid);
            model.addAttribute("TimeId",TimeId);
        }
        return "personal/ajax/option";

    }

    /**
     * NO. 0022-4 - liming
     * 科室变更保存
     * @param firstdep
     * @param seconddep
     * @param doctor
     * @param time
     * @param req
     * @return
     */
    @RequestMapping("/upd")
    public String upd(String firstdep,String seconddep,String doctor,String time,HttpServletRequest req){
        String id = req.getParameter("Oid");
        RegOffice regOffice = regOfficeService.findById(Integer.valueOf(id));
        Integer firstdept = Integer.parseInt(firstdep);
        Integer seconddept = Integer.parseInt(seconddep);
        Integer doctors = Integer.parseInt(doctor);
        Integer times = Integer.parseInt(time);
        regOffice.setFirstdepartmentId(firstdept);
        regOffice.setSeconddepartmentsId(seconddept);
        regOffice.setDoctorId(doctors);
        regOffice.setTimeId(times);
        regOfficeService.updateReg(regOffice);
        regOfficeService.changeStatus(Integer.valueOf(id));
        return "redirect:order";
    }

    /**
     * NO. 0061 - liming
     * 保存就诊人
     * @return
     */
    @RequestMapping("/newin")
    public String newin(){
        return "personal/newin";
    }
    @RequestMapping("/newinsite")
    public String newinsite(HttpServletRequest req,HttpSession httpSession){
        User user = (User) httpSession.getAttribute("user");
        String names = req.getParameter("names");
        String card = req.getParameter("card");
        String sexs = req.getParameter("sexs");
        String ages = req.getParameter("ages");
        Userinfo userinfo = UserInfoService.findByUserId(user.getId());
        //非本人信息类型为1
        userinfo.setTypes(1);
        userinfo.setAge(Integer.valueOf(ages));
        userinfo.setIdcard(card);
        userinfo.setUname(names);
        userinfo.setSex(sexs);
        UserInfoService.save(userinfo);
        return "redirect:newview";
    }

    /**
     * NO. 0062 - liming
     * 添加就诊人前往挂号
     * @return
     */
    @RequestMapping("/upreg")
    public String upreg(HttpServletRequest req,HttpSession httpSession) {
        return "reg/regOffice";
    }
    @RequestMapping("/toreg")
    public String toreg(HttpServletRequest req,HttpSession httpSession){
        User user = (User) httpSession.getAttribute("user");
        String names = req.getParameter("names");
        String card = req.getParameter("card");
        String sexs = req.getParameter("sexs");
        String ages = req.getParameter("ages");
        Userinfo userinfo = UserInfoService.findByUserId(user.getId());
        //非本人信息类型为1
        userinfo.setTypes(1);
        userinfo.setAge(Integer.valueOf(ages));
        userinfo.setIdcard(card);
        userinfo.setUname(names);
        userinfo.setSex(sexs);
        UserInfoService.save(userinfo);
        return "reg/regOffice";
    }

    /**
     * NO. 0063 - liming
     * 查看就诊人列表及分页、记数、将身份证生日进行用*号代替
     * @return
     */
    @RequestMapping("/newview")
    public String newview(){
        return "personal/newview";
    }
    @RequestMapping("/newviews")
    public String newviews(Model model, HttpSession httpSession,@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "4") Integer pageSize){
        User user = (User) httpSession.getAttribute("user");
        PageInfo<Userinfo> pageInfo = UserInfoService.findReplace(user.getId(),Integer.valueOf(pageNum),Integer.valueOf(pageSize));
        Integer count = UserInfoService.CountPeopleByUserId(user.getId());
        Integer cout = 8 - count;
        model.addAttribute("count",count);
        model.addAttribute("cout",cout);
        model.addAttribute("userinfos",pageInfo);
        return "personal/pagedate/newinPageDate";
    }

    /**
     * NO. 0064 - liming
     * 删除就诊人信息
     * @param req
     * @return
     */
    @RequestMapping("/delnewin")
    public String delnewin( HttpServletRequest req){
        String id = req.getParameter("id");
        Userinfo userinfo = UserInfoService.findByUserInfoId(Integer.valueOf(id));
        UserInfoService.delByUserInfoId(userinfo);
        return "personal/newview";
    }


    /**
     * 获取验证码
     * @param httpSession
     * @param req
     * @return
     */
    @RequestMapping("/sendMsg")
    @ResponseBody
    public Map<String,Object> sendMsg(HttpSession httpSession,HttpServletRequest req){
        User user = (User) httpSession.getAttribute("user");
        String phone = req.getParameter("phone");
        SmsUtil.getPhonemsg(phone);
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        String currentTime = sf.format(calendar.getTime());
        String hash = SmsUtil.getCode();
        Map<String,Object> requestMap = new HashMap<>();
        requestMap.put("hash",hash);
        requestMap.put("currentTime",currentTime);
        Phone ph = phoneService.findPhone(phone);
        if(user.getPhoneId() != null){
            Phone phones = UserInfoService.findByPhoneId(user.getPhoneId());
            phones.setPhone(phone);
            phones.setCode(Integer.valueOf(hash));
            UserInfoService.updatePhone(phones);
        }
        return requestMap;
    }
    /**
     * 更改手机号
     * @param httpSession
     * @param req
     * @return
     */
    @RequestMapping("/changeone")
    @ResponseBody
    public Result register(HttpSession httpSession,HttpServletRequest req){
        User user = (User) httpSession.getAttribute("user");
        String phone = req.getParameter("phone");
        String codeLine = req.getParameter("codeLine");

        Phone p = phoneService.findPhone(phone);

        if (phone!=null&&p.getCode().equals(Integer.valueOf(codeLine))){
            User users = UserInfoService.findById(user.getId());
            users.setPhone(phone);
            UserInfoService.update(users);
        }

        return new Result(CodeStatus.OK,true,+p.getCode()+"");
    }

}
